package cn.bbstone.pisces2.client.base;

import cn.bbstone.pisces2.client.task.impl.FileTask;
import cn.bbstone.pisces2.comm.fli.FliSavePoint;
import cn.hutool.core.util.StrUtil;

import java.util.*;

/**
 * BFileRsp.id = BFileReq.id = reqId = md5(filepath)
 * filepath is relative to server.dir
 */
public class ClientCache {

    /** current running Tasks, key: fileNo(lineNum in fli.idx) */
    private static Map<Long, FileTask> runningTasks = new HashMap<>();

    private static FliSavePoint fliSavePoint = null;
    /** ms */
    private static long totalCostTime = 0;
    // ------------- only for ChunkedFile mode end ----------------


    /**
     *
     * @param fileNo - line number in fli.idx file
     * @return
     */
    public static FileTask getTask(Long fileNo) {
        return runningTasks.get(fileNo);
    }

    public static String runningTaskInfo() {
        List<Long> runningFileTaskNo = new ArrayList<>();
        runningTasks.forEach((k,v) -> {
            runningFileTaskNo.add(k);
        });
        return StrUtil.toString(runningFileTaskNo);
    }

    /**
     *
     * @param fileNo - line number in fli.idx file
     * @param task - File Receive & Storage path
     */
    public synchronized static void addTask(Long fileNo, FileTask task) {
        runningTasks.put(fileNo, task);
    }

    public synchronized static void removeTask(Long fileNo) {
        runningTasks.remove(fileNo);
    }


    public static void cleanAll() {
        runningTasks = Collections.emptyMap();
    }

    public static void accumulateCostTime(long oneFileTransferCostTimeMs) {
        totalCostTime += oneFileTransferCostTimeMs;
    }

    public static long getTotalCostTimeMs() {
        return totalCostTime;
    }

    /**
     * task size
     * @return
     */
    public static int size() {
        return runningTasks.size();
    }

    public static void setFliSavePoint(FliSavePoint savePoint) {
        fliSavePoint = savePoint;
    }

    public static long getSpCount() {
        return fliSavePoint == null ? 0L: fliSavePoint.getCount();
    }
}
